/**
 * Description:
 * Class Name:CallableStatementTest
 * Date:2022/4/9 18:42
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_4_执行SQL语句的方式._13_4_4_使用CallableStatement调用存储过程;

import java.io.FileInputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
import java.util.Properties;

public class CallableStatementTest {
    private String driver;
    private String url;
    private String user;
    private String pwd;

    public void initParam(String paramFile) throws Exception{
        // 使用Properties类来加载属性文件
        var props = new Properties();
        props.load(new FileInputStream(paramFile));
        // 从配置文件中获取相应数据
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }

    public void callProcedure(String sql_procedure) throws Exception{
        try(
                // 使用驱动管理获取连接对象
                Connection connection = DriverManager.getConnection(url, user, pwd);
                // 用获取的连接对象来创建CallableStatement
                CallableStatement cstmt = connection.prepareCall(sql_procedure);
                ){
            // 使用setXxx()方法来传入参数设置值
            cstmt.setInt(1, 4);
            cstmt.setInt(2, 5);
            // 使用registerOutParameter()方法来注册传出参数
            cstmt.registerOutParameter(3, Types.INTEGER);

            // 执行sql语句
            cstmt.execute();
            System.out.println("执行结果是：" + cstmt.getInt(3));
        }
    }

    public static void main(String[] args) throws Exception{
        // 获得初始化所用的参数
        var ct = new CallableStatementTest();
        ct.initParam("Chapter_13_mysql.ini");

        // 使用反射来加载驱动
        Class.forName(ct.driver);

        // 执行存储过程的sql语句，?是作为存储过程参数的占位符
        String sql_for_procedure = "{call add_pro(?,?,?)}";
        ct.callProcedure(sql_for_procedure);
    }
}
